package com.hellohoper.script.config.admin.app.zookeeper;

import com.hellohoper.assembly.common.utils.util.JsonUtils;
import com.hellohoper.script.config.admin.app.dao.pojo.ScriptConfig;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * zookeeper配置同步
 * Created by hk on 17/8/18.
 */
@Service
public class ZookeeperService {

    @Autowired
    private CuratorFramework curatorFramework;

    /**
     * 将配置同步到ZK
     *
     * @param scriptConfig 配置
     * @throws Exception Exception
     */
    public void addZkConifig(ScriptConfig scriptConfig) throws Exception {

        String path = "/" + scriptConfig.getAppName() + "/" + scriptConfig.getScriptName();
        // 判断节点是否存
        Stat stat = curatorFramework.checkExists().forPath(path);
        // 持久节点不存在，创建节点
        if (stat == null) {
            curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);
        }
        // 写入数据
        curatorFramework.setData().forPath(path, JsonUtils.toJson(scriptConfig).getBytes());
    }

    /**
     * 更新ZK配置
     *
     * @param scriptConfig 配置
     * @throws Exception Exception
     */
    public void updateZkConfig(ScriptConfig scriptConfig) throws Exception {

        String path = "/" + scriptConfig.getAppName() + "/" + scriptConfig.getScriptName();
        // 判断节点是否存
        Stat stat = curatorFramework.checkExists().forPath(path);
        // 持久节点不存在，创建节点
        if (stat == null) {
            curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);
        }
        // 写入数据
        curatorFramework.setData().forPath(path, JsonUtils.toJson(scriptConfig).getBytes());
    }

    /**
     * 删除ZK配置
     *
     * @param scriptConfig 配置
     * @throws Exception Exception
     */
    public void deleteZkConfig(ScriptConfig scriptConfig) throws Exception {

        String path = "/" + scriptConfig.getAppName() + "/" + scriptConfig.getScriptName();
        // 判断节点是否存
        Stat stat = curatorFramework.checkExists().forPath(path);
        // 持久节点存在，删除节点
        if (stat != null) {
            curatorFramework.delete().deletingChildrenIfNeeded().forPath(path);
        }
    }
}
